/**
 * 报销标准
 */
import React, { Component } from 'react';
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Popconfirm, Popover, Badge, Modal, message, Radio, Input } from 'antd';
import { messages, getDefaultSetOfBook, deepCopy } from "share/common"
import errorMessage from 'share/errorMessage'
import TableList from '../table-list'
import requestAndExpenseService from '../request-and-expense-settings.service'
import SlideFrameDetail from 'containers/expense-reimbursement-control/expense-standard/reimbursement/new-rule'
import reimburseService from 'containers/expense-reimbursement-control/expense-standard/reimbursement/reimbursement.service'
import {batchOperations} from "components/template/wrapped-table-params/batch-operations";
import CurrencySettingService from '../../setting/currency-setting/currency-setting.service';
import chooserData from 'share/chooserData'
import debounce from 'lodash.debounce';

const Search = Input.Search;
const RadioGroup = Radio.Group;

class ReimbursementStandard extends Component {

  constructor(props){
    super(props);
    this.searchNumber = debounce(this.searchNumber, 500);
  }

  state = {
    loading: false,
    searchForm :[
      {
        id: 'levelCode',
        dataIndex: 'levelCode',
        label: messages('expense-8.key1')/*层级*/,
        component: (
          <RadioGroup>
            <Radio value="COMPANY">{messages('expense-8.key2')/*公司*/}</Radio>
            <Radio value="SET_OF_BOOK">{messages('expense-8.key3')/*帐套*/}</Radio>
          </RadioGroup>
        ),
        tagParser: value => {
          return value === "COMPANY" ? messages('expense-8.key2')/*公司*/ : messages('expense-8.key3')/*帐套*/;
        },
      }, {
        id: 'distLevelOrgIds',
        dataIndex: 'companys',
        label: messages('expense-8.key4')/*启用公司*/,
        component: 'Chooser',
        props: {
          labelKey: 'name',
          valueKey: 'id',
          type: 'priority_company'
        },
        parser: value => ({
          distLevelOrgIds: value ? value.map(item => item.id) : null
        })
      },
      {
        id: 'expenseTypeIds',
        dataIndex: 'expenseTypes',
        label: messages('common.expense.type')/*费用类型*/,
        component: 'Chooser',
        props: {
          labelKey: 'name',
          valueKey: 'id',
          selectorItem: deepCopy(chooserData['selectInvoiceType'])
        },
        parser: value => ({
          expenseTypeIds: value ? value.map(item => item.id) : null
        })
      }],
    searchName: ''
  };

  infoData = {
    dataSource: { explain: messages('expense-8.key5')/*您可以在此页面配置报销标准，系统会根据您配置的规则自动对报销单中费用的合规性（如：是否超过标准）、合理性（如：是否重复报销）进行管控。*/ },
    attributes: [{ title: messages('expense-8.key6')/*说明*/, dataIndex: 'explain', span: 24 }]
  };

  slideFrameInfo = {
    title: messages('expense-8.key7')/*报销标准*/,
    content: SlideFrameDetail,
    params: {}
  };

  columns = [{
    title: messages('expense-8.key1')/*层级*/,
    dataIndex: 'levelCode',
    render: value => value === 'COMPANY' ? messages('expense-8.key2')/*公司*/ :
      messages('expense-8.key3')/*帐套*/
  }, {
    title: messages('expense-8.key8')/*所属组织*/,
    dataIndex: 'levelOrgName',
    render: value => <Popover content={value} placement="topLeft">{value}</Popover>
  }, {
    title: messages('expense-8.key4')/*启用公司*/,
    dataIndex: 'companys',
    render: value => {
      if (value && value.length) {
        let companyNames = [];
        value.map(item => companyNames.push(item.name));
        return <Popover content={companyNames.join(', ')} placement="topLeft">{companyNames.join(', ')}</Popover>
      }
      return messages('expense-8.key9')/*通用*/
    }
  }, {
    title: messages('expense-8.key10')/*规则名称*/,
    dataIndex: 'name',
    render: value => <Popover content={value} placement="topLeft">{value}</Popover>
  }, {
    title: messages('common.expense.type')/*费用类型*/,
    dataIndex: 'expenseTypes',
    render: value => {
      let showExpense = [];
      if (value && value.length) {
        value.map(item => showExpense.push(item.name));
        return (
          <Popover placement="topLeft"
                   content={showExpense.join(', ')}>{showExpense.join(', ')}</Popover>
        )
      }
      return '-'
    }
  },  {
    title: messages('expense-8.key11')/*适用人员*/,
    dataIndex: 'userGroups',
    render: value => {
      let showUser = [];
      (value || []).map(item => showUser.push(item.name));
      return showUser.length ? (
        <Popover placement="topLeft"
                 content={showUser.join('、')}>{showUser.join('、')}</Popover>
      ) : messages('expense-8.key9')/*通用*/
    }
  }, {
    title: messages('expense-8.key12')/*报销方式*/,
    dataIndex: 'controlModeType',
    render: value => {
      const obj = {
        'SINGLE': messages('expense-8.key13')/*单条管控*/,
        'PERIOD': messages('expense-8.key14')/*周期管控*/,
        'SUMMARY': messages('expense-8.key15')/*单据内汇总管控*/
      };
      return obj[value];
    }
  }, {
    title: messages('common.column.status')/*状态*/,
    dataIndex: 'status',
    width: '10%',
    render: value => (
      <Badge
        status={value ? 'success' : 'error'}
        text={value ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
      />
    )
  }, {
    title: messages('common.operation')/*操作*/,
    dataIndex: 'ruleOID',
    width: '10%',
    render: (value, record) => (
      record.readOnly ? (
        <span onClick={e => e.stopPropagation()} className="font-disabled">{messages('common.delete')/*删除*/}</span>
      ) : (
        <Popconfirm
          title={messages('expense-8.key16')/*确认删除该设置？*/}
          onConfirm={() => this.handleDelete(value)}
        >
          <a onClick={e => e.stopPropagation()}>{messages('common.delete')/*删除*/}</a>
        </Popconfirm>
      )
    )
  }];

  componentDidMount() {
    Promise.all([this.getAllSetOfBooks(), this.getSetOfBook()])
      .then(() => {
        const { searchForm, setOfBooks, defaultSetOfBooks } = this.state;
        searchForm.some(item => {
          if (item.id === 'expenseTypeIds') {
            item.props.selectorItem.searchForm.unshift({
              type: 'select',
              id: 'setOfBooksId',
              label: messages('expense-8.key17')/*账套*/,
              options: setOfBooks.map(item => {
                return {
                  label: item.setOfBooksName,
                  value: item.id
                };
              }),
              defaultValue: defaultSetOfBooks.id,
              isRequired: true
            });
            return item;
          }
        });
      });
  };

  getSetOfBook = async () => {
    const res = await getDefaultSetOfBook();
    if (res.data && res.data.defaultSetOfBooksId) {
      const defaultSetOfBooks = {
        id: res.data.defaultSetOfBooksId,
        name: res.data.defaultSetOfBooksName
      };
      this.slideFrameInfo.params.setOfBook = defaultSetOfBooks;
      await this.setState({ defaultSetOfBooks });
    }
  };

  getAllSetOfBooks = async () => {
    const res = await CurrencySettingService.getSetOfBooks();
    await this.setState({ setOfBooks: res.data });
  };

  handleDelete = ruleOID => {
    Modal.confirm({
      title: messages('expense-8.key18')/*确认删除？*/,
      content: messages('expense-8.key19')/*分配的公司将不可用该规则，你还要继续吗？*/,
      onOk: () => {
        this.setState({ loading: true });
        reimburseService.deleteRule(ruleOID).then(() => {
          this.setState({ loading: false });
          this.advancedTableRef.getList();
          message.success(messages('common.delete.success',{arg1: ""})/*{arg1} 删除成功*/);
        }).catch(e => {
          this.setState({ loading: false });
          errorMessage(e.response);
        })
      },
    })
  };

  service = (page, size, searchParams) => {
    const { searchName: name } = this.state;
    let params = {
      page,
      size,
      ...searchParams,
      businessType: 1001,
      name
    };
    return requestAndExpenseService.getReimbursementList(params);
  };

  //规则创建成功后直接进详情页
  afterClose = ruleOID => {
    let url = menuRoute.getPageUrlByKey('reimbursement-standard-detail').replace(':ruleOID', ruleOID);
    ruleOID && this.context.router.push(url);
  };

  searchNumber = async (e) => {
    console.log(e);
    await this.setState({ searchName: e });
    this.advancedTableRef.getList(true, 1);
  };

  render() {
    const { loading, searchForm } = this.state;
    let tableParams =  batchOperations({
      rowKey: 'ruleOID'
    }, [{
      type: 'DELETE',
      service: requestAndExpenseService.batchDeleteReimbursementStandard,
      onOk: () => this.advancedTableRef.getList(),
      extraParams: { businessType: 1001 }
    }, {
      type: 'ENABLE',
      service: requestAndExpenseService.batchOpenOrCloseReimbursementStandard,
      onOk: () => this.advancedTableRef.getList(),
      extraParams: { businessType: 1001 }
    }, {
      type: 'DISABLE',
      service: requestAndExpenseService.batchOpenOrCloseReimbursementStandard,
      onOk: () => this.advancedTableRef.getList(),
      extraParams: { businessType: 1001 }
    }], this);
    return (
      <div className="full-height-page">
        <TableList
          subPageKey=""
          subPageInfo={{
            key: 'reimbursement-standard-detail',
            replaceParams: ['ruleOID']
          }}
          infoData={this.infoData}
          slideFrameInfo={this.slideFrameInfo}
          afterClose={this.afterClose}
          more={
            <Search
              style={{ width: '200px', float: 'right' }}
              className="input-search input-search-left"
              placeholder={messages('expense-8.key20')/*请输入规则名称*/}
              onChange={(e) => this.searchNumber(e.target.value)}
            />
          }
          tableParams={{
            loading,
            rowKey: 'ruleOID',
            searchForm,
            columns: this.columns,
            service: this.service,
            onRef: ref => this.advancedTableRef = ref,
            ...tableParams
          }}
        />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return { }
}

ReimbursementStandard.contextTypes = {
  router: React.PropTypes.object
};

export default connect(mapStateToProps)(ReimbursementStandard)
